package com.dgut.lotterySystem.service.impl;

import com.dgut.lotterySystem.common.errorcode.ServiceErrorCodeConstants;
import com.dgut.lotterySystem.common.pojo.exception.ServiceException;
import com.dgut.lotterySystem.common.utils.*;
import com.dgut.lotterySystem.service.IVerificationCodeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    //为了区别不同缓存信息，在存入的信息前加入相对应的业务名称

    private final String VERIFICATION_CODE_TEMPLATE="SMS_476815534";
    private final String VERIFICATION_CODE_PREFIX="VERIFICATION_CODE_";
    private final Long VERIFICATION_CODE_TIMEOUT=60L;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SMSUtil smsUtil;

    private static final Logger logger= (Logger) LoggerFactory.getLogger(VerificationCodeServiceImpl.class);

    /**
     * 生成验证码，存redis
     * @param phoneNumber
     */
    @Override
    public void setVerificationCode(String phoneNumber) {
        //验证手机号码
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //生成验证码
        String verificationCode=CaptchaUtil.setCaptcha(4);
        System.out.println("验证码"+verificationCode);

        //发送短信
        Map<String,String> map=new HashMap<>();
        map.put("code",verificationCode);
        smsUtil.sendMessage(VERIFICATION_CODE_TEMPLATE,phoneNumber,JacksonUtil.writeValueAsString(map));

        //缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,verificationCode,VERIFICATION_CODE_TIMEOUT);
    }

    /**
     * 获取验证码
     * @param phoneNumber
     * @return
     */
    @Override
    public String getVerificationCode(String phoneNumber) {
        //验证手机号码
        if(!RegexUtil.checkMobile(phoneNumber)){
            System.out.println(phoneNumber);
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
